package com.xuecheng.order.service;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.framework.domain.task.XcTaskHis;
import com.xuecheng.order.dao.XcTaskHisRepository;
import com.xuecheng.order.dao.XcTaskRepository;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Optional;

/**
 * @author ShengJinFeng
 * @version V1.0
 * @ClassName XcTaskService
 * @Description (任务业务层)
 * @date 2020/3/14 10:38
 * @since V1.0
 */
@Service
public class XcTaskService {

    @Autowired
    private XcTaskRepository xcTaskRepository;

    @Autowired
    private XcTaskHisRepository xcTaskHisRepository;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * @Description 查询某个时间点之前的n条任务
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    public List<XcTask> queryTaskUpdateTimeBefore(Date updateTime, int n){
        PageRequest pageRequest = PageRequest.of(0, n);
        Page<XcTask> taskPage = xcTaskRepository.findByUpdateTimeBefore(pageRequest, updateTime);
        List<XcTask> content = taskPage.getContent();
        return content;
    }

    /**
     * @Description 发送消息
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    @Transactional
    public void sendMsg(XcTask xcTask){
        if (xcTask == null){
            return;
        }
        String exchange = xcTask.getMqExchange();
        String routingkey = xcTask.getMqRoutingkey();
        rabbitTemplate.convertAndSend(exchange,routingkey,xcTask);
        //更新任务时间为当前时间
        xcTask.setUpdateTime(new Date());
        xcTaskRepository.save(xcTask);
    }

    /**
     * @Description 检查任务是否可以执行，如果可以执行，更新任务的版本号
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    @Transactional
    public XcTask checkTask(XcTask xcTask){
        //先查询该任务是否存在
        XcTask task = xcTaskRepository.findByIdAndVersion(xcTask.getId(), xcTask.getVersion());
        if (task == null){
            return null;
        }
        task.setVersion(task.getVersion()+1);
        return xcTaskRepository.save(task);
    }

    /**
     * @Description 完成任务
     * @author ShengJinFeng
     * @date 2020/3/14
     */
    @Transactional
    public void finishTask(String taskId){
        Optional<XcTask> optional = xcTaskRepository.findById(taskId);
        if (optional.isPresent()){
            XcTask xcTask = optional.get();
            //添加任务历史记录
            XcTaskHis xcTaskHis = new XcTaskHis();
            BeanUtils.copyProperties(xcTask,xcTaskHis);
            xcTaskHisRepository.save(xcTaskHis);
            //删除任务
            xcTaskRepository.delete(xcTask);
        }
    }

}
